package com.springboot.file.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.springboot.file.entity.CustCreditInfo;
import com.springboot.file.entity.FinPledgeAssetManage;
import com.springboot.file.repository.CustCreditInfoRepository;
import com.springboot.file.repository.FinPledgeAssetManageRepository;
import com.springboot.file.util.DateUtil;
import com.springboot.file.util.easyexcel.annotation.EasyImport;
import com.springboot.file.util.easyexcel.constant.BusinessType;
import com.springboot.file.util.easyexcel.listener.AbstractBusinessListener;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 客户挂账信息导入监听器
 */
@Slf4j
@Component
@EasyImport(value = BusinessType.CUST_CREDIT, description = "客户挂账信息导入")
public class CustCreditListener extends AbstractBusinessListener<CustCreditInfo> {

    /**
     * 每批次处理数量，避免一次性处理过多数据
     */
    private static final int SUB_BATCH_SIZE = 100;

    /**
     * 记录已保存的记录总数
     */
    private final AtomicInteger savedCount = new AtomicInteger(0);

    /**
     * 记录更新的记录总数
     */
    private final AtomicInteger updatedCount = new AtomicInteger(0);

    @Resource
    private CustCreditInfoRepository custCreditInfoRepository;
    
    @Resource
    private FinPledgeAssetManageRepository finPledgeAssetManageRepository;

    @Override
    protected int saveData(List<CustCreditInfo> dataList) {
        if (ObjectUtil.isEmpty(dataList)) {
            log.info("没有数据需要保存");
            return 0;
        }

        log.info("开始处理客户挂账数据，记录数: {}", dataList.size());

        try {
            // 分批次处理数据，减小单次处理量
            List<List<CustCreditInfo>> subLists = CollUtil.split(dataList, SUB_BATCH_SIZE);
            log.info("客户挂账数据分为{}个批次处理", subLists.size());

            for (int i = 0; i < subLists.size(); i++) {
                processBatch(subLists.get(i));

                // 帮助 GC 清理内存
                subLists.set(i, null);
            }

            log.info("客户挂账数据导入完成，成功保存 {} 条记录，更新 {} 条记录",
                    savedCount.get(), updatedCount.get());

            return savedCount.get() + updatedCount.get();
        } catch (Exception e) {
            log.error("处理客户挂账数据时发生异常", e);
            return 0;
        }
    }

    /**
     * 处理一个批次的数据
     *
     * @param batchData 当前批次数据
     */
    private void processBatch(List<CustCreditInfo> batchData) {
        if (CollUtil.isEmpty(batchData)) {
            return;
        }
        
        log.info("开始处理批次数据，记录数: {}", batchData.size());
        
        // 从批次数据中提取订单编号和凭证编号
        List<String> orderNos = extractDistinctValues(batchData, CustCreditInfo::getOrderNo);
        List<String> voucherNos = extractDistinctValues(batchData, CustCreditInfo::getNeedPayAccEvidenceCode);
        
        if (CollUtil.isEmpty(orderNos) || CollUtil.isEmpty(voucherNos)) {
            log.warn("批次中存在无效数据，订单编号或凭证编号为空");
            return;
        }
        
        // 查询已存在的记录并创建索引
        Map<String, CustCreditInfo> existingRecordsMap = findExistingRecordsMap(orderNos, voucherNos);
        
        // 分类记录为更新或新增
        RecordBatch recordBatch = classifyRecords(batchData, existingRecordsMap);
        
        // 批量更新记录
        updateExistingRecords(recordBatch.getRecordsToUpdate());
        
        // 批量保存新记录
        saveNewRecords(recordBatch.getRecordsToAdd());
        
        // 处理可融资产融资管理表数据
        processFinPledgeAssetManage(batchData);
    }
    
    /**
     * 提取数据列表中的唯一值
     * 
     * @param <T> 函数返回类型
     * @param dataList 数据列表
     * @param mapper 映射函数
     * @return 唯一值列表
     */
    private <T> List<T> extractDistinctValues(List<CustCreditInfo> dataList, 
                                             java.util.function.Function<CustCreditInfo, T> mapper) {
        return dataList.stream()
                .map(mapper)
                .filter(ObjectUtil::isNotEmpty)
                .distinct()
                .collect(Collectors.toList());
    }
    
    /**
     * 查询已存在的记录并创建按键值映射的索引
     * 
     * @param orderNos 订单编号列表
     * @param voucherNos 凭证编号列表
     * @return 已存在记录的映射
     */
    private Map<String, CustCreditInfo> findExistingRecordsMap(List<String> orderNos, List<String> voucherNos) {
        List<CustCreditInfo> existingRecords = findExistingRecords(orderNos, voucherNos);
        return createRecordIndexMap(existingRecords);
    }
    
    /**
     * 查询已存在的记录
     * 
     * @param orderNos 订单编号列表
     * @param voucherNos 凭证编号列表
     * @return 已存在记录列表
     */
    private List<CustCreditInfo> findExistingRecords(List<String> orderNos, List<String> voucherNos) {
        LambdaQueryWrapper<CustCreditInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(CustCreditInfo::getOrderNo, orderNos)
                .in(CustCreditInfo::getNeedPayAccEvidenceCode, voucherNos);
        return custCreditInfoRepository.list(queryWrapper);
    }
    
    /**
     * 创建记录的索引映射
     * 
     * @param records 记录列表
     * @return 记录映射
     */
    private Map<String, CustCreditInfo> createRecordIndexMap(List<CustCreditInfo> records) {
        return records.stream()
                .collect(Collectors.toMap(
                    custCreditInfo -> generateKey(custCreditInfo.getOrderNo(), custCreditInfo.getNeedPayAccEvidenceCode()),
                    custCreditInfo -> custCreditInfo,
                    (existing, replacement) -> existing // 如果有重复键，保留第一个
                ));
    }
    
    /**
     * 记录分类结果
     */
    @Getter
    private static class RecordBatch {
        private final List<CustCreditInfo> recordsToUpdate = new ArrayList<>();
        private final List<CustCreditInfo> recordsToAdd = new ArrayList<>();

        public void addToUpdate(CustCreditInfo custCreditInfo) {
            recordsToUpdate.add(custCreditInfo);
        }
        
        public void addToInsert(CustCreditInfo custCreditInfo) {
            recordsToAdd.add(custCreditInfo);
        }
    }
    
    /**
     * 将记录分类为更新或新增
     * 
     * @param batchData 批次数据
     * @param existingMap 已存在记录的映射
     * @return 分类结果
     */
    private RecordBatch classifyRecords(List<CustCreditInfo> batchData, Map<String, CustCreditInfo> existingMap) {
        RecordBatch result = new RecordBatch();
        
        for (CustCreditInfo importedRecord : batchData) {
            if (hasEmptyKeys(importedRecord)) {
                log.warn("跳过无效数据: 订单编号或凭证编号为空");
                continue;
            }
            
            String key = generateKey(importedRecord.getOrderNo(), importedRecord.getNeedPayAccEvidenceCode());
            CustCreditInfo existingRecord = existingMap.get(key);
            
            if (existingRecord != null) {
                prepareForUpdate(existingRecord, importedRecord);
                result.addToUpdate(existingRecord);
            } else {
                prepareForInsert(importedRecord);
                result.addToInsert(importedRecord);
            }
        }
        
        return result;
    }
    
    /**
     * 检查记录是否有空键
     * 
     * @param custCreditInfo 记录
     * @return 是否有空键
     */
    private boolean hasEmptyKeys(CustCreditInfo custCreditInfo) {
        return ObjectUtil.isEmpty(custCreditInfo.getOrderNo())
                || ObjectUtil.isEmpty(custCreditInfo.getNeedPayAccEvidenceCode());
    }
    
    /**
     * 批量更新已存在的记录
     * 
     * @param recordsToUpdate 要更新的记录列表
     */
    private void updateExistingRecords(List<CustCreditInfo> recordsToUpdate) {
        if (recordsToUpdate.isEmpty()) {
            return;
        }
        
        boolean updateResult = custCreditInfoRepository.updateBatchById(recordsToUpdate);
        if (updateResult) {
            updatedCount.addAndGet(recordsToUpdate.size());
            log.info("成功更新 {} 条记录", recordsToUpdate.size());
        } else {
            log.error("批量更新失败，涉及 {} 条记录", recordsToUpdate.size());
            logErrorSamplesIfNeeded(recordsToUpdate);
        }
    }
    
    /**
     * 批量保存新记录
     * 
     * @param recordsToAdd 要保存的新记录列表
     */
    private void saveNewRecords(List<CustCreditInfo> recordsToAdd) {
        if (recordsToAdd.isEmpty()) {
            return;
        }
        
        boolean saveResult = custCreditInfoRepository.saveBatch(recordsToAdd);
        if (saveResult) {
            savedCount.addAndGet(recordsToAdd.size());
            log.info("成功保存 {} 条新记录", recordsToAdd.size());
        } else {
            log.error("批量保存失败，涉及 {} 条记录", recordsToAdd.size());
            logErrorSamplesIfNeeded(recordsToAdd);
        }
    }
    
    /**
     * 如果记录数量较少，记录错误样本
     * 
     * @param records 记录列表
     */
    private void logErrorSamplesIfNeeded(List<CustCreditInfo> records) {
        if (records.size() <= 5) {
            logErrorSamples(records);
        }
    }
    
    /**
     * 生成用于查询的组合键
     *
     * @param orderNo 订单编号
     * @param voucherNo 凭证编号
     * @return 组合键
     */
    private String generateKey(String orderNo, String voucherNo) {
        return orderNo + "|" + voucherNo;
    }
    
    /**
     * 准备更新记录
     *
     * @param existingRecord 已存在的记录
     * @param importedRecord 导入的记录
     */
    private void prepareForUpdate(CustCreditInfo existingRecord, CustCreditInfo importedRecord) {
        // 复制所有属性，排除特定字段
        BeanUtil.copyProperties(importedRecord, existingRecord, 
                "chargeOrderNo", "createUser", "createDatetime");
        
        // 更新日期和时间信息
        existingRecord.setLastUpdateDatetime(LocalDateTime.now());
        
        // 确保日期格式统一
        formatDates(existingRecord);
    }
    
    /**
     * 准备新增记录
     *
     * @param newRecord 新记录
     */
    private void prepareForInsert(CustCreditInfo newRecord) {
        // 生成挂账单据编号
        newRecord.setChargeOrderNo(IdUtil.simpleUUID());
        
        // 设置创建时间
        newRecord.setCreateDatetime(LocalDateTime.now());
        
        // 确保日期格式统一
        formatDates(newRecord);
    }
    
    /**
     * 统一处理日期格式
     *
     * @param custCreditInfo 记录
     */
    private void formatDates(CustCreditInfo custCreditInfo) {
        // 转换日期格式
        custCreditInfo.setClearAccountDate(DateUtil.convertObjToString(custCreditInfo.getClearAccountDate(), DateUtil.DATE_FORMATTER_3));
        custCreditInfo.setEvidenceDate(DateUtil.convertObjToString(custCreditInfo.getEvidenceDate(), DateUtil.DATE_FORMATTER_3));
        custCreditInfo.setPlanReceiveDate(DateUtil.convertObjToString(custCreditInfo.getPlanReceiveDate(), DateUtil.DATE_FORMATTER_3));
        custCreditInfo.setReceiveDate(DateUtil.convertObjToString(custCreditInfo.getReceiveDate(), DateUtil.DATE_FORMATTER_3));
    }

    /**
     * 记录错误样本信息，便于排查问题
     *
     * @param records 记录列表
     */
    private void logErrorSamples(List<CustCreditInfo> records) {
        log.error("错误记录样本:");
        for (int i = 0; i < Math.min(records.size(), 5); i++) {
            CustCreditInfo custCreditInfo = records.get(i);
            log.error("样本 #{}: 订单号={}, 凭证号={}", 
                    i + 1, custCreditInfo.getOrderNo(), custCreditInfo.getNeedPayAccEvidenceCode());
        }
    }

    /**
     * 处理可融资产融资管理表数据
     * 
     * @param batchData 客户挂账信息批次数据
     */
    private void processFinPledgeAssetManage(List<CustCreditInfo> batchData) {
        if (CollUtil.isEmpty(batchData)) {
            return;
        }
        
        log.info("开始处理可融资产融资管理表数据，源数据记录数: {}", batchData.size());
        
        // 按应付账款凭证编号分组
        Map<String, List<CustCreditInfo>> voucherGroupedMap = groupByVoucherNo(batchData);
        
        List<FinPledgeAssetManage> toUpdateList = new ArrayList<>();
        List<FinPledgeAssetManage> toAddList = new ArrayList<>();
        
        // 处理每个凭证编号组
        for (Map.Entry<String, List<CustCreditInfo>> entry : voucherGroupedMap.entrySet()) {
            processVoucherGroup(entry.getKey(), entry.getValue(), toUpdateList, toAddList);
        }
        
        // 执行批量更新和新增
        executeBatchUpdates(toUpdateList, toAddList);
    }
    
    /**
     * 按应付账款凭证编号对数据进行分组
     */
    private Map<String, List<CustCreditInfo>> groupByVoucherNo(List<CustCreditInfo> batchData) {
        return batchData.stream()
                .filter(custCreditInfo -> ObjectUtil.isNotEmpty(custCreditInfo.getNeedPayAccEvidenceCode()))
                .collect(Collectors.groupingBy(CustCreditInfo::getNeedPayAccEvidenceCode));
    }
    
    /**
     * 处理单个凭证编号组的数据
     */
    private void processVoucherGroup(String voucherNo, List<CustCreditInfo> records, 
                                    List<FinPledgeAssetManage> toUpdateList, 
                                    List<FinPledgeAssetManage> toAddList) {
        if (CollUtil.isEmpty(records)) {
            return;
        }
        
        // 从组中获取一条记录作为参考
        CustCreditInfo sampleRecord = records.get(0);
        
        // 根据应付账款凭证编号查询可融资产融资管理表
        List<FinPledgeAssetManage> existingAssets = findAssetsByVoucherNo(voucherNo);
        
        if (CollUtil.isNotEmpty(existingAssets)) {
            // 凭证编号存在，更新记录
            updateExistingAssetsByVoucher(existingAssets, sampleRecord, toUpdateList);
        } else {
            // 凭证编号不存在，处理每条记录
            processRecordsWithoutExistingVoucher(records, voucherNo, toUpdateList, toAddList);
        }
    }
    
    /**
     * 根据凭证编号查询资产记录
     */
    private List<FinPledgeAssetManage> findAssetsByVoucherNo(String voucherNo) {
        LambdaQueryWrapper<FinPledgeAssetManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FinPledgeAssetManage::getNeedPayAccEvidenceCode, voucherNo);
        return finPledgeAssetManageRepository.list(queryWrapper);
    }
    
    /**
     * 根据订单编号查询资产记录
     */
    private List<FinPledgeAssetManage> findAssetsByOrderNo(String orderNo) {
        LambdaQueryWrapper<FinPledgeAssetManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FinPledgeAssetManage::getPurchaseOrderNo, orderNo);
        return finPledgeAssetManageRepository.list(queryWrapper);
    }
    
    /**
     * 更新已存在凭证编号的资产记录
     */
    private void updateExistingAssetsByVoucher(List<FinPledgeAssetManage> existingAssets, 
                                             CustCreditInfo sampleRecord,
                                             List<FinPledgeAssetManage> toUpdateList) {
        log.info("根据凭证编号 {} 找到 {} 条可融资产记录，准备更新", 
                sampleRecord.getNeedPayAccEvidenceCode(), existingAssets.size());
        
        // 更新所有匹配记录的核销状态
        for (FinPledgeAssetManage asset : existingAssets) {
            asset.setIsCancel(sampleRecord.getNeedPayAccStatus());
            asset.setLastUpdatedStamp(LocalDateTime.now());
            toUpdateList.add(asset);
        }
    }
    
    /**
     * 处理没有现有凭证编号匹配的记录
     */
    private void processRecordsWithoutExistingVoucher(List<CustCreditInfo> records, 
                                                    String voucherNo,
                                                    List<FinPledgeAssetManage> toUpdateList, 
                                                    List<FinPledgeAssetManage> toAddList) {
        for (CustCreditInfo creditInfo : records) {
            String orderNo = creditInfo.getOrderNo();
            if (ObjectUtil.isEmpty(orderNo)) {
                continue;
            }
            
            // 查询订单相关的资产记录
            List<FinPledgeAssetManage> orderAssets = findAssetsByOrderNo(orderNo);
            
            if (CollUtil.isNotEmpty(orderAssets)) {
                processOrderWithExistingAssets(orderAssets, creditInfo, voucherNo, toUpdateList, toAddList);
            } else {
                // 订单没有关联记录，创建新记录
                createNewAssetRecord(creditInfo, toAddList);
            }
        }
    }
    
    /**
     * 处理有现有订单资产记录的情况
     */
    private void processOrderWithExistingAssets(List<FinPledgeAssetManage> orderAssets, 
                                              CustCreditInfo creditInfo,
                                              String voucherNo,
                                              List<FinPledgeAssetManage> toUpdateList, 
                                              List<FinPledgeAssetManage> toAddList) {
        
        // 检查订单资产记录特征
        AssetRecordFeatures features = analyzeOrderAssets(orderAssets, voucherNo);
        
        if (features.hasEmptyVoucherRecord) {
            // 有空凭证编号的记录，更新第一个找到的空记录
            updateFirstEmptyVoucherRecord(orderAssets, voucherNo, creditInfo, toUpdateList);
        } else if (features.voucherExists) {
            // 凭证编号已存在，更新所有匹配记录的核销状态
            updateMatchingVoucherRecords(orderAssets, voucherNo, creditInfo, toUpdateList);
        } else {
            // 凭证编号不存在且没有空记录，创建新记录并关联
            createRelatedAssetRecord(orderAssets, creditInfo, toAddList);
        }
    }
    
    /**
     * 分析订单资产记录的特征
     */
    private AssetRecordFeatures analyzeOrderAssets(List<FinPledgeAssetManage> orderAssets, String voucherNo) {
        AssetRecordFeatures features = new AssetRecordFeatures();
        
        // 提取所有关联订单的凭证编号
        Set<String> existingVoucherNos = orderAssets.stream()
                .map(FinPledgeAssetManage::getNeedPayAccEvidenceCode)
                .filter(ObjectUtil::isNotEmpty)
                .collect(Collectors.toSet());
        
        // 检查是否有空凭证编号的记录
        features.hasEmptyVoucherRecord = orderAssets.stream()
                .anyMatch(asset -> ObjectUtil.isEmpty(asset.getNeedPayAccEvidenceCode()));
        
        // 检查当前凭证编号是否已存在
        features.voucherExists = existingVoucherNos.contains(voucherNo);
        
        return features;
    }
    
    /**
     * 资产记录特征类
     */
    private static class AssetRecordFeatures {
        boolean hasEmptyVoucherRecord;
        boolean voucherExists;
    }
    
    /**
     * 更新第一个空凭证编号的记录
     */
    private void updateFirstEmptyVoucherRecord(List<FinPledgeAssetManage> orderAssets,
                                             String voucherNo,
                                             CustCreditInfo creditInfo,
                                             List<FinPledgeAssetManage> toUpdateList) {
        for (FinPledgeAssetManage orderAsset : orderAssets) {
            if (ObjectUtil.isEmpty(orderAsset.getNeedPayAccEvidenceCode())) {
                orderAsset.setNeedPayAccEvidenceCode(voucherNo);
                orderAsset.setIsCancel(creditInfo.getNeedPayAccStatus());
                orderAsset.setLastUpdatedStamp(LocalDateTime.now());
                toUpdateList.add(orderAsset);
                log.info("根据订单编号 {} 找到凭证编号为空的记录，更新凭证编号和核销状态", creditInfo.getOrderNo());
                break; // 只更新第一个空记录
            }
        }
    }
    
    /**
     * 更新匹配凭证编号的记录
     */
    private void updateMatchingVoucherRecords(List<FinPledgeAssetManage> orderAssets,
                                            String voucherNo,
                                            CustCreditInfo creditInfo,
                                            List<FinPledgeAssetManage> toUpdateList) {
        for (FinPledgeAssetManage orderAsset : orderAssets) {
            if (voucherNo.equals(orderAsset.getNeedPayAccEvidenceCode())) {
                orderAsset.setIsCancel(creditInfo.getNeedPayAccStatus());
                orderAsset.setLastUpdatedStamp(LocalDateTime.now());
                toUpdateList.add(orderAsset);
                log.info("根据订单编号 {} 找到凭证编号相同的记录，更新核销状态", creditInfo.getOrderNo());
            }
        }
    }
    
    /**
     * 创建关联的新资产记录
     */
    private void createRelatedAssetRecord(List<FinPledgeAssetManage> orderAssets,
                                        CustCreditInfo creditInfo,
                                        List<FinPledgeAssetManage> toAddList) {
        FinPledgeAssetManage newAsset = createNewFinPledgeAsset(creditInfo);
        
        // 查找最新的记录作为参考
        FinPledgeAssetManage referenceAsset = findMostRecentAsset(orderAssets);
        
        // 检查参考资产是否为空
        if (referenceAsset == null) {
            log.warn("根据订单编号 {} 没有找到可参考的记录，将创建不带参考信息的新记录", creditInfo.getOrderNo());
            // 设置锁定标识为"未锁定"
            newAsset.setIsLock("0");
            toAddList.add(newAsset);
            return;
        }
        
        log.info("根据订单编号 {} 找到 {} 条记录，选择最近更新的记录作为参考", 
                creditInfo.getOrderNo(), orderAssets.size());
        
        // 复制金融产品信息
        copyFinancialInfo(referenceAsset, newAsset);
        
        // 设置上级凭证编号为最新记录的凭证编号
        if (ObjectUtil.isNotEmpty(referenceAsset.getNeedPayAccEvidenceCode())) {
            newAsset.setParentEvidenceCode(referenceAsset.getNeedPayAccEvidenceCode());
            log.info("设置上级凭证编号为: {}", referenceAsset.getNeedPayAccEvidenceCode());
        }
        
        // 设置锁定标识为"未锁定"
        newAsset.setIsLock("0");
        
        toAddList.add(newAsset);
        log.info("根据订单编号 {} 创建新记录，上级凭证编号: {}", 
                creditInfo.getOrderNo(), newAsset.getParentEvidenceCode());
    }
    
    /**
     * 复制金融产品信息
     * @param source 源资产记录，可能为null
     * @param target 目标资产记录
     */
    private void copyFinancialInfo(FinPledgeAssetManage source, FinPledgeAssetManage target) {
        if (ObjectUtil.isEmpty(source) || ObjectUtil.isEmpty(target)) {
            log.warn("复制金融产品信息时源或目标为null，跳过复制");
            return;
        }
        
        target.setFinProductId(source.getFinProductId());
        target.setFinCreditApplyId(source.getFinCreditApplyId());
        target.setFinUtilizeApplyId(source.getFinUtilizeApplyId());
    }
    
    /**
     * 创建全新的资产记录
     */
    private void createNewAssetRecord(CustCreditInfo creditInfo, List<FinPledgeAssetManage> toAddList) {
        FinPledgeAssetManage newAsset = createNewFinPledgeAsset(creditInfo);
        // 设置锁定标识为"未锁定"
        newAsset.setIsLock("0");
        toAddList.add(newAsset);
        log.info("根据订单编号 {} 未找到记录，新增记录", creditInfo.getOrderNo());
    }
    
    /**
     * 执行批量更新和新增操作
     */
    private void executeBatchUpdates(List<FinPledgeAssetManage> toUpdateList, List<FinPledgeAssetManage> toAddList) {
        // 批量更新
        if (CollUtil.isNotEmpty(toUpdateList)) {
            boolean updateResult = finPledgeAssetManageRepository.updateBatchById(toUpdateList);
            log.info("更新可融资产融资管理表记录 {} 条，结果: {}", 
                    toUpdateList.size(), updateResult ? "成功" : "失败");
        }
        
        // 批量新增
        if (CollUtil.isNotEmpty(toAddList)) {
            boolean saveResult = finPledgeAssetManageRepository.saveBatch(toAddList);
            log.info("新增可融资产融资管理表记录 {} 条，结果: {}", 
                    toAddList.size(), saveResult ? "成功" : "失败");
        }
    }
    
    /**
     * 查找最近更新的资产记录作为参考
     * 优先按最后更新时间倒序，如果为空则按创建时间倒序
     * 
     * @param assetList 资产记录列表
     * @return 最近更新的资产记录
     */
    private FinPledgeAssetManage findMostRecentAsset(List<FinPledgeAssetManage> assetList) {
        if (CollUtil.isEmpty(assetList)) {
            return null;
        }
        
        // 先尝试查找有最后更新时间的记录
        List<FinPledgeAssetManage> assetsWithUpdateTime = assetList.stream()
                .filter(asset -> ObjectUtil.isNotEmpty(asset.getLastUpdatedStamp()))
                .sorted((a1, a2) -> a2.getLastUpdatedStamp().compareTo(a1.getLastUpdatedStamp()))
                .collect(Collectors.toList());
        
        if (CollUtil.isNotEmpty(assetsWithUpdateTime)) {
            // 返回最后更新时间最近的资产
            FinPledgeAssetManage mostRecent = assetsWithUpdateTime.get(0);
            log.info("根据最后更新时间 {} 选择参考记录", mostRecent.getLastUpdatedStamp());
            return mostRecent;
        }
        
        // 如果没有有效的最后更新时间，则按创建时间排序
        List<FinPledgeAssetManage> assetsWithCreateTime = assetList.stream()
                .filter(asset -> ObjectUtil.isNotEmpty(asset.getCreateTimestamp()))
                .sorted((a1, a2) -> a2.getCreateTimestamp().compareTo(a1.getCreateTimestamp()))
                .collect(Collectors.toList());
        
        if (CollUtil.isNotEmpty(assetsWithCreateTime)) {
            // 返回创建时间最近的资产
            FinPledgeAssetManage mostRecent = assetsWithCreateTime.get(0);
            log.info("根据创建时间 {} 选择参考记录", mostRecent.getCreateTimestamp());
            return mostRecent;
        }
        
        // 如果都没有时间信息，返回第一个
        log.info("无法找到有时间信息的记录，使用第一条记录作为参考");
        return assetList.get(0);
    }

    /**
     * 根据客户挂账信息创建新的可融资产融资管理记录
     * 
     * @param creditInfo 客户挂账信息
     * @return 新的可融资产融资管理记录
     */
    private FinPledgeAssetManage createNewFinPledgeAsset(CustCreditInfo creditInfo) {
        FinPledgeAssetManage asset = new FinPledgeAssetManage();
        
        // 设置ID
        asset.setFinPledgeId(IdUtil.simpleUUID());
        
        // 收款公司信息对应企业信息
        asset.setCustId(creditInfo.getReceiveCompanyMdgCode());
        asset.setCustName(creditInfo.getReceiveCompanyName());
        
        // 合同信息
        asset.setContractNo(creditInfo.getThisPayContractNo());
        
        // 订单和凭证信息
        asset.setPurchaseOrderNo(creditInfo.getOrderNo());
        asset.setNeedPayAccEvidenceCode(creditInfo.getNeedPayAccEvidenceCode());
        
        // 核销状态
        asset.setIsCancel(creditInfo.getNeedPayAccStatus());
        
        // 创建时间
        asset.setCreateTimestamp(LocalDateTime.now());
        
        return asset;
    }

} 